package org.dna.metronomo.persistence.impl;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * MyBatis TypeHandler for the convertion of booelan <-> integer.
 *
 * @author andrea
 */
public class IntBoolTypeHandler extends BaseTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        boolean value = (Boolean) parameter;
        ps.setInt(i, value ? 1 : 0);
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int value = rs.getInt(columnName);
        return convertToBool(value);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int value = cs.getInt(columnIndex);
        return convertToBool(value);
    }

    private Boolean convertToBool(int value) {
        if (value != 0 && value != 1) {
            return null;
        }
        if (value == 0) {
            return Boolean.FALSE;
        } else {
            return Boolean.TRUE;
        }
    }
}
